package v1

import (
	"ginblog/model"
	"ginblog/utils/errmsg"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// AddArticle 添加文章
func AddArticle(c *gin.Context) {
	var data model.Article
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status":  errmsg.ERROR,
			"data":    data,
			"message": err.Error(),
		})
		return
	}
	// 用户名可以入库
	code = model.CreateArticle(&data)

	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    data,
		"message": errmsg.GetErrMsg(code),
	})

}

// GetArticlesOfCategory 查询分类下的所有文章
func GetArticlesOfCategory(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pagesize"))
	pageNum, _ := strconv.Atoi(c.Query("pagenum"))
	cid, _ := strconv.Atoi(c.Param("cid"))
	// if sizeErr != nil || numErr != nil || idErr != nil {
	// 	msg := fmt.Sprintf("sizeErr：%s；idErr：%s；numErr：%s", sizeErr, numErr, idErr)
	// 	c.JSON(http.StatusOK, gin.H{
	// 		"status":  errmsg.ERROR,
	// 		"data":    nil,
	// 		"total":   0,
	// 		"message": msg,
	// 	})
	// 	return
	// }

	if pageSize == 0 {
		// 当查询条件为-1时就不启用
		pageSize = -1
	}

	if pageNum == 0 {
		// 当查询条件为-1时就不启用
		pageNum = 2
	}

	data, code, total := model.GetArticlesOfCategory(cid, pageSize, pageNum)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    data,
		"total":   total,
		"message": errmsg.GetErrMsg(code),
	})

}

// GetArticleInfo 查询单个文章信息
func GetArticleInfo(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"status":  errmsg.ERROR,
			"message": err,
		})
		return
	}
	data, code := model.GetArticleInfo(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    data,
		"message": errmsg.GetErrMsg(code),
	})
}

// GetArticles  查询文章列表
func GetArticles(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pagesize"))
	pageNum, _ := strconv.Atoi(c.Query("pagenum"))
	title := c.Query("title")

	if pageSize == 0 {
		// 当查询条件为-1时就不启用
		pageSize = -1
	}

	if pageNum == 0 {
		// 当查询条件为-1时就不启用
		pageNum = 2
	}

	data, code, total := model.GetArticles(title, pageSize, pageNum)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    data,
		"total":   total,
		"message": errmsg.GetErrMsg(code),
	})
}

// EditArticle 编辑文章
func EditArticle(c *gin.Context) {
	var data model.Article
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"status":  errmsg.ERROR,
			"message": err,
		})
		return
	}
	c.ShouldBindJSON(&data)
	code = model.EditArticle(id, &data)

	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}

// DeleteArticle 删除文章
func DeleteArticle(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"status":  errmsg.ERROR,
			"message": err,
		})
		return
	}

	code = model.DeleteArticle(id)

	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}
